package com.ad.pet.app.account;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;

import com.ad.pet.DaggerMainActivityCompent;
import com.ad.pet.Logger;
import com.ad.pet.MainActivity;
import com.ad.pet.R;
import com.ad.pet.app.Navigation;
import com.ad.pet.app.RxDisposable;
import com.ad.pet.common.data.http.BusCall;
import com.ad.pet.common.data.utils.SpUtil;
import com.ad.pet.common.data.utils.ui.ToastUtil;
import com.ad.pet.common.structure.events.Events;
import com.ad.pet.common.structure.events.RxBus;
import com.ad.pet.common.structure.mvp.BasePresenter;
import com.ad.pet.common.structure.ui.activity.AppToolbarActivity;
import com.ad.pet.constant.Constant;
import com.ad.pet.models.remote.PayResult;
import com.ad.pet.models.remote.Wxpay;
import com.ad.pet.utils.AndroidInterface;
import com.ad.pet.wxapi.PayContract;
import com.ad.pet.wxapi.PayPresenter;
import com.ad.pet.wxapi.WXPayUtils;
import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.just.agentweb.AgentWeb;
import com.umeng.socialize.UMShareAPI;

import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

/**
 * 这个页面很多地方都需要使用到
 * 所以使用了很多的方法重载到达这个页面，不同的重载方法有不同的使用场景
 * 1、通用的web页面做一些基础的页面展示
 * 2、购物部分使用包括商品详情页
 * 3、一些需要特殊处理的部分，因为结算页面使用的web页并且还需要传递一些post参数
 * 4、其他需要使用该页面的地方
 * Created by SEELE on 2018/3/29.
 */

public class CommonWebActitivity extends AppToolbarActivity implements PayContract.View {
    @BindView(R.id.mContainer)
    LinearLayout mContainer;
    private String mTitle;
    private AgentWeb mAgentWeb;
    @Inject
    RxDisposable mRxDisposable;

    @Inject
    PayPresenter mPayPresenter;
    int payType;//0购买会员，1商城

    //        private RxPermissions mRxPermissions;
    private boolean mIsFinish;//是否为Mainactivity里面的首页fragment的顶部栏的banner跳转的，true是，false否
    private String mEndUrl = "";
    private boolean mIsShowTop;
//    ProgressDialog mProgressDialog;

    static final int SDK_PAY_FLAG = 1;
    PayResult type;
    private Handler deliver = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG:
//                    String resault = msg.obj.toString();
//                    LogUtils.e("pay_resault",resault);
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    String notifyUrl = payResult.getNotifyUrl();
                    // 判断resultStatus 为9000则代表支付成功
                    Logger.e("result_alipay:" + resultInfo + "|" + resultStatus + "|" + notifyUrl);
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。

                        ToastUtil.getToastUtil().showShort(getString(R.string.pay_success));
//17166573284
//                        Navigation.goCompleteOrder(mActivity, mSn_id);
//                        setResult(RESULT_OK, new Intent());
                        if ( mEndUrl.contains("#/MonthcardList")) {
                            Navigation.goCommonWebView(mActivity, getString(R.string.conpuons), "/#/mycoupon?token=" + SpUtil.getInstance().getString(Constant.ACCESS_TOKEN), false, MainActivity.REQUEST_GO_MALL);
                        } else {
                            Navigation.goPacketDetail(mActivity, type.getOrder_id());
                        }
                        finish();
//                        RxBus.getDefault().post(new Events.PayStatusCallback(notifyUrl, "alipay", resultInfo));
                    } else {//支付失败
                        ToastUtil.getToastUtil().showShort(getString(R.string.pay_failed));

                    }
                    break;
            }
        }
    };

    @Override
    protected void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
        mStatusLayoutManager.showContent();
        mTitle = getIntent().getStringExtra("title");
        mToolbar.setTitle(mTitle);

//        mRxDisposable.add(RxBus.getDefault().toObservable(WebTitle.class)
//                .observeOn(AndroidSchedulers.mainThread()).subscribe(new BusCall<WebTitle>() {
//                    @Override
//                    public void call(WebTitle webTitle) {
//                        mToolbar.setTitle(webTitle.getTitle());
//                    }
//                }));
        mIsShowTop = getIntent().getBooleanExtra("isShow", true);
        if (mIsShowTop) {
            mToolbar.setVisibility(View.VISIBLE);
        } else {
            mToolbar.setVisibility(View.GONE);
        }
        mToolbar.setBackOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //按返回键操作并且能回退网页
                if (mAgentWeb.getWebCreator().getWebView().canGoBack()) {
                    //后退
                    mAgentWeb.getWebCreator().getWebView().goBack();
                    return;
                } else {
                    finish();
                }


            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && mAgentWeb.getWebCreator().getWebView().canGoBack()) {
            mAgentWeb.getWebCreator().getWebView().goBack();//返回上个页面
            return true;
        }
        return super.onKeyDown(keyCode, event);//退出H5界面
    }

    @Override
    protected int contentLayout() {
        return R.layout.activity_common_web;
    }

    @Override
    protected void clickRetry(View v) {

    }


    @Override
    protected void initViews() {
//        mRxPermissions = new RxPermissions(this);
//        mProgressDialog = DialogUtil.createProgressDialog(this);
//        mProgressDialog.show();
        mPayPresenter.onCreate(this);
        String url = getIntent().getStringExtra("url");

        mIsFinish = getIntent().getBooleanExtra("isFinish", false);


//        syncCookie();
//        AgentWebConfig.getCookiesByUrl(getString(R.string.top_host_point));


        /**
         * 判断url中是否包含域名，如果包含了就不要拼接域名了，如果没有包含，就要拼接一下主域名
         */
        if (!TextUtils.isEmpty(url)) {
            if (url.contains("http")) {
                mEndUrl = url;
            } else {
                mEndUrl = getString(R.string.ip_host) + url;
            }

        }

        setWebview(mEndUrl);

    }


    @Override
    protected void initData() {
        mPayPresenter.onCreate(this);
    }

    @Override
    protected void initEvents() {
        mRxDisposable.add(RxBus.getDefault().toObservable(Events.AddCarts.class)
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new BusCall<Events.AddCarts>() {
                    @Override
                    public void call(Events.AddCarts webTitle) {
                        setWebview(mEndUrl);
                    }
                }));
        mRxDisposable.add(RxBus.getDefault().toObservable(PayResult.class).subscribe(new Action1<PayResult>() {
            @Override
            public void call(final PayResult payResult) {
                type = payResult;

//                if ("5".equals(type.getPayType())){
//                    DialogUtil.createDialog(mActivity, "", "是否使用账户余额进行支付？", true, "取消", null, "确认", new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            mPayPresenter.upPayresult(payResult.getOrder_id(), payResult.getPayType());
//                        }
//                    }).show();
//                }else {
                    mPayPresenter.upPayresult(payResult.getOrder_id(), payResult.getPayType());
//                }



            }
        }));
        mRxDisposable.add(RxBus.getDefault().toObservable(Events.PayStatusCallback.class).subscribe(new Action1<Events.PayStatusCallback>() {
            @Override
            public void call(final Events.PayStatusCallback payResult) {

                ToastUtil.getToastUtil().showShort("支付成功");
                if (mEndUrl.contains("#/MonthcardList")) {
                    Navigation.goCommonWebView(mActivity, getString(R.string.conpuons), "/#/mycoupon?token=" + SpUtil.getInstance().getString(Constant.ACCESS_TOKEN), false, MainActivity.REQUEST_GO_MALL);
                } else {
                    Navigation.goPacketDetail(mActivity, type.getOrder_id());
                }
                finish();

            }
        }));

    }

    @Override
    public void initInject() {
        DaggerMainActivityCompent.builder().applicationComponent(getApplicationComponent())

                .activityModule(getActivityModule()).build().inject(this);
    }

    @Override
    protected BasePresenter getPresenter() {
        return null;
    }


    /**
     * webview设置url
     * 注意，如果是订单确认页面，也就是说morder不为空，那么我们的请求就要来mposturl参数了
     * 如果是支付url，那么我们就请求支付，如果是正常的普通url那么我们就直接请求url就好了
     *
     * @param url 请求url
     */
    private void setWebview(String url) {
//        if (url.substring(url.length() - 1, url.length()).equals("/")) {
//            url = url.substring(0, url.length() - 1);
//        }
//        String token = "0";
//        if (hasLogin()){
//            token = getAccessToken();
//        }
//        String endActionUrl  = "lang=" + SpUtil.getInstance().getString(Constant.LANGUAGE, "cn") + "&cy=" + SpUtil.getInstance().getString(Constant.MONEY_ID, "1")+"&status=1&platform=Android&key="+token;
//        if (url.contains("?")) {
//            url = url + "&"+endActionUrl;
//        } else {
//            url = url+"?"+endActionUrl;
//        }

        mAgentWeb = AgentWeb.with(mActivity)
                .setAgentWebParent(mContainer, new LinearLayout.LayoutParams(-1, -1)).useDefaultIndicator(getResources().getColor(R.color.colorAccent), 1)
                .createAgentWeb()
                .ready()
                .go(url);
        Logger.e(url);
        mAgentWeb.getJsInterfaceHolder().addJavaObject("android", new AndroidInterface(mAgentWeb, mActivity));
        mAgentWeb.getAgentWebSettings().getWebSettings().setDomStorageEnabled(true);


    }

    @Override
    public void onDestroy() {
        if (mAgentWeb != null)
            mAgentWeb.destroy();
        if (mRxDisposable != null)
            mRxDisposable.clear();
        UMShareAPI.get(this).release();
        super.onDestroy();

    }

    @Override
    public void onPause() {
        if (mAgentWeb != null)
            mAgentWeb.getWebLifeCycle().onPause();
        super.onPause();
    }

    @Override
    public void onResume() {
        if (mAgentWeb != null)
            mAgentWeb.getWebLifeCycle().onResume();
        super.onResume();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        if (data == null)
            return;
        switch (requestCode) {
            case MainActivity.REQUEST_GO_MALL:
                setResult(RESULT_OK, data);
                finish();
                break;
        }
    }

//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            if (mAgentWeb.getWebCreator().getWebView().canGoBack()) {
//                mAgentWeb.getWebCreator().getWebView().goBack();//返回上一页面
//                return true;
//            }
//        }
//        return super.onKeyDown(keyCode, event);
//    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void error(String msg) {
        ToastUtil.getToastUtil().showShort(msg);
    }


    @Override
    public void upPayresultSuccess(PayResult payResult) {

        int type1 = Integer.valueOf(payResult.getPayment_type());
        if (type1 == 1) {

            WXPayUtils wxPayUtils = new WXPayUtils(mActivity);
            if (wxPayUtils.isWxAppInstalledAndSupported()) {


                Wxpay wxpay = new Wxpay(payResult.getAppid(), payResult.getPartnerid(), payResult.getPrepay_id(), payResult.getNonce_str(), payResult.getTimestamp(), payResult.getPackageq(), payResult.getSign(), "notify_url");
                wxPayUtils.doPay(new Gson().toJson(wxpay));
                Logger.d("jsonString--->" + new Gson().toJson(wxpay));
            }
        } else if (type1 == 2) {
            final String orderInfo = payResult.getAli_pay_str();   // 订单信息

            Runnable payRunnable = new Runnable() {

                @Override
                public void run() {
                    PayTask alipay = new PayTask(mActivity);
                    Map<String, String> result = alipay.payV2(orderInfo, false);
//                    result.put("notify_url", payUrl.getNotify_url());
                    Message msg = new Message();
                    msg.what = SDK_PAY_FLAG;
                    msg.obj = result;
                    deliver.sendMessage(msg);
                }
            };
            // 必须异步调用
            Thread payThread = new Thread(payRunnable);
            payThread.start();
        }else if (type1==5){
            ToastUtil.getToastUtil().showShort("支付成功");
            if (mEndUrl.contains("#/MonthcardList")) {
                Navigation.goCommonWebView(mActivity, getString(R.string.conpuons), "/#/mycoupon?token=" + SpUtil.getInstance().getString(Constant.ACCESS_TOKEN), false, MainActivity.REQUEST_GO_MALL);
            } else {
                Navigation.goPacketDetail(mActivity, type.getOrder_id());
            }
            finish();
        }
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        UMShareAPI.get(this).onSaveInstanceState(outState);
    }

}
